package com.ccll.handler;

import com.ccll.domain.common.CustomException;
import com.ccll.domain.http.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * @author Seon
 * @date 2022/11/13 13:22
 */
@Slf4j
@ResponseBody
@ControllerAdvice(annotations = {Controller.class, RestController.class})
public class GlobalExceptionHandler {
    private static final String DUPLICATE_KEY = "Duplicate entry";

    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public Result<?> exceptionHandler(SQLIntegrityConstraintViolationException exception) {
        log.error(exception.getMessage());
        if (exception.getMessage().contains(DUPLICATE_KEY)) {
            String[] split = exception.getMessage().split(" ");
            String msg = "失败，" + split[2] + "已经存在了，改一个叭";
            return Result.error(msg, 0);
        }
        return Result.error("失败，请检查信息", 0);
    }

    @ExceptionHandler(CustomException.class)
    public Result<?> exceptionHandler(CustomException exception) {
        log.error(exception.getMessage());
        return Result.error(exception.getMessage(), 0);
    }
}
